package base.day18.array;

public class Array2 {
    public static void main(String[] args) {
        //用二分法查询number对应有序数组中的索引
        int[] array={1,2,3,4,5,6,7,8,9};
        int number=3;
        int index=findArrayIndex(array, number);
        System.out.println(index);
    }

    private static int findArrayIndex(int[] array, int number) {
        //定义查找范围
        int min=0;
        int max=array.length-1;
        //循环查找
        while(true){
            //中间位置的索引
            int mid=(min+max)/2;  //
            //mid索引对应的值 和number比较
            //当mid索引对应的值>number
            if (array[mid]>number){
                max=mid-1;
            }
            //当mid索引对应的值小于number
            else if (array[mid]<number){
                min=mid+1;
            }
            //当mid索引对应的值=number时
            else{
                return mid;
            }
        }
    }
}
